// pages/personala/detailed/index.js
var Bmob = require('../../../utils/bmob.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [

    ],
  },
  goHome(){
    // 
    wx.switchTab({
      url: '/pages/home/index',
    })
  },
  // 分享进来领取弹出框
  affirm: function () {
    // this.setData({
    //   isShare: false
    // })


  },
  complete: function () {
    this.setData({
      isSuccess: false
    })
  },

  endPassword: function (i) {
    console.log(i);
    var entry = i.detail.value.entry;
    var id = this.data.id;
    var password = this.data.password;


    if (entry == "") {
      wx.showModal({
        title: '提示',
        content: '请输入口令',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }

    if (entry != password) {
      wx.showModal({
        title: '提示',
        content: '输入口令错误',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }

    this.addData(id);
    this.setData(
      {
        "isShare": false
      }
    );
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    Bmob.Cloud.run('test', {}, {
      success: function (result) {
        console.log(result);
      },
      error: function (error) {
      }
    })

    var isShare = options.isShare ? options.isShare : false;  
    var id = options.id ? options.id : "c9a73f386b";  //id是当前的红包id
    if (isShare){
      console.log('用户5555点击取消')
      var Diary = Bmob.Object.extend("envelopes");
      var query = new Bmob.Query(Diary);
      var currentUser = Bmob.User.current();
      var objectId = currentUser.id;    //objectId是当前登录的用户id
      var that=this;
      query.get(id, {
        success: function (result) {
          var title = result.get("uid");
          console.log("aaaaa", result, objectId);
          if (result.get("uid").id == objectId) {
            that.setData({
              isShare: false,
            });
            wx.showModal({
              title: '提示',
              content: '发送人不能领哦！快去邀请好友来玩吧~',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })

            
          }

          if (result.get("isPay") != true) {
            that.setData({
              isShare: false,
            });

            return;
          }
        },
        error: function (object, error) {
          // 查询失败
          console.log('用户点击取消22')
        }
      });
    }

    
    

    console.log("参数", options);


    // var that = this;


    this.setData({
      id: id,
      isShare: isShare
    });




    //获取红包相关信息
    this.getHongbao(id);




  },
  addData: function (id) {
    var that = this;
    // 处理发红包逻辑
    var Diary = Bmob.Object.extend("envelopes");
    var query = new Bmob.Query(Diary);
    query.include("uid");
    
    query.get(id, {
      success: function (result) {
        // The object was retrieved successfully.
        console.log("该日记标题为" + result.get("balance"));
        var number = result.get("quantity") + 1;
        console.log(number);
        if (result.get("num") <= result.get("quantity")) {
          wx.showModal({
            title: '提示',
            content: '抱歉，红包已经领完了',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          return;
        }


        //领取数量+1
        var Diary = Bmob.Object.extend("envelopes");
        var query = new Bmob.Query(Diary);

        // 这个 id 是要修改条目的 id，你在生成这个存储并成功时可以获取到，请看前面的文档
        query.get(id, {
          success: function (result) {
            // 回调中可以取得这个 diary 对象的一个实例，然后就可以修改它了
            result.set('quantity', number);
            result.save();
            // The object was retrieved successfully.
          },
          error: function (object, error) {

          }
        });



        var Diary = Bmob.Object.extend("receive");
        var query = new Bmob.Query(Diary);
        query.include("uid");
        var eid = Bmob.Object.createWithoutData("envelopes", id);
        query.equalTo("eid", eid);
        // 查询所有数据
        query.find({
          success: function (results) {
            var rid;
            var amount;
            console.log("共查询到 " + results.length + " 111条记录");
            // 循环处理查询到的数据
            for (var i = 0; i < results.length; i++) {
              var object = results[i];
              console.log(object.id + ' - ' + object.get('uid'));
              if (object.get('uid') == undefined) {
                rid = object.id

                amount = object.get('amount');
                // 增加余额
                that.addMoney(amount);
                console.log("领取红包ID" + object.id);

                break;
              }
            }

            //领取的用户 设置领取
            var Diary = Bmob.Object.extend("receive");
            var query = new Bmob.Query(Diary);
            var currentUser = Bmob.User.current();
            var objectId = currentUser.id;
            var post = Bmob.Object.createWithoutData("_User", objectId);
            query.include("uid");
            console.log("用户ID", objectId, post)
        

            // 这个 id 是要修改条目的 id，你在生成这个存储并成功时可以获取到，请看前面的文档
            query.get(rid, {
              success: function (result) {



                var Diary = Bmob.Object.extend("envelopes");
                var query = new Bmob.Query(Diary);
                query.get("id", {
                  success: function (result) {
                    // The object was retrieved successfully.
                    console.log("该日记标题为" + result.get("uid"));
                    
                  },
                  error: function (result, error) {
                    console.log("查询失败");
                  }
                });
                // 回调中可以取得这个 diary 对象的一个实例，然后就可以修改它了
                result.set('uid', post);
                // result.set('amount', "amount");
                result.save();
                // The object was retrieved successfully.
              },
              error: function (object, error) {

              }
            });


          },
          error: function (error) {
            console.log("查询失败: " + error.code + " " + error.message);
          }
        });





      },
      error: function (result, error) {
        console.log("查询失败");
      }
    });




  },

  addMoney: function (ye) {
    var that = this;
    //金额存入钱包
    var Diary = Bmob.Object.extend("_User");
    var query = new Bmob.Query(Diary);
    var currentUser = Bmob.User.current();
    var usid = currentUser.id;

    // 这个 id 是要修改条目的 id，你在生成这个存储并成功时可以获取到，请看前面的文档
    query.get(usid, {
      success: function (result) {

        var money = result.get("balance") == undefined ? 0 : result.get("balance");
        console.log(money);
        money = parseFloat(money) + ye;
        console.log("iiiii" + money);
        //金额存入钱包
        var Diary = Bmob.Object.extend("_User");
        var query = new Bmob.Query(Diary);

        // 这个 id 是要修改条目的 id，你在生成这个存储并成功时可以获取到，请看前面的文档
        query.get(usid, {
          success: function (result) {
            // 回调中可以取得这个 diary 对象的一个实例，然后就可以修改它了
            result.set('balance', money);
            result.save();

            // 领取成功后逻辑
            that.setData({
              money: ye,
              isSuccess: true
            })
            var id = that.data.id;
            that.getHongbao(id, 1);

          },
          error: function (object, error) {

          }
        });


      },
      error: function (object, error) {

      }
    });
  },


  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    var id = this.data.id;
    return {
      title: '得到红包一个，赶快来领取吧',
      path: '/pages/personala/detailed/index?isShare=1&id=' + id,
      success: function (res) {
        // 转发成功
        console.log('/pages/personala/detailed/index?isShare=1&id=' + id);
        wx.showModal({
          title: '提示',
          content: '恭喜，红包分享成功',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      },



      fail: function (res) {
        // 转发失败
        wx.showModal({
          title: '提示',
          content: '失败',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
  },
  getHongbao: function (id, l) {
    // l 的意思是是否领取过红包
    var that = this;
    var Diary = Bmob.Object.extend("envelopes");
    var query = new Bmob.Query(Diary);
    query.include("uid");
    query.get(id, {
      success: function (result) {
        that.setData({
          result: result,
          password: result.get("password")
        })
      },
      error: function (result, error) {
        console.log("查询失败");
      }
    });


    var Diary = Bmob.Object.extend("receive");
    var query = new Bmob.Query(Diary);
    query.include("uid");


    var eid = Bmob.Object.createWithoutData("envelopes", id);
    query.equalTo("eid", eid);

    // 查询所有数据
    query.find({
      success: function (results) {
        that.setData({
          results: results
        })
        console.log("共查询到 " + results.length + " 条记录");
        var currentUser = Bmob.User.current();
        var uid = currentUser.id;
        // 循环处理查询到的数据
        for (var i = 0; i < results.length; i++) {
          var object = results[i];
          console.log(object.id + '4344 - ' + object.get('uid'));

          if (object.get('uid') != undefined && uid == object.get('uid').objectId) {
            that.setData({
              isShare: false,
            });
            if (!l) {
              wx.showModal({
                title: '提示',
                content: '您已经领取过红包了，请关注其他红包',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
              break;
              return;
            }
          }

        }

      },
      error: function (error) {
        console.log("查询失败: " + error.code + " " + error.message);
      }
    });


  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


})